import type {
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteRecordRaw,
} from 'vue-router'
import NProgress from '@/utils/nprogress'
import { Auth } from '@/utils/auth'
import router from '@/router'
import TASK_API from '@/api/dcyx/task.api'
import { usePermissionStore, useUserStore } from '@/store'
import { ROLE_ROOT } from '@/constants'

export function setupPermission() {
  // 白名单路由
  const whiteList = ['/login']

  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    console.log('to.path', to.path)

    const isLogin = Auth.isLoggedIn()
    // console.log('isLogin', isLogin)
    if (isLogin) {
      // 登录后，首跳做一次 Gate 检查（缓存 60s）
      const needGateCheck = to.path === '/' || to.path === '/dashboard'
      if (needGateCheck) {
        const now = Date.now()
        const ttlMs = 60 * 1000
        const lastTs = Number(localStorage.getItem('GATE_TODAY_STATUS_TS') || '0')
        const lastVal = localStorage.getItem('GATE_TODAY_STATUS')
        const cachedOk = lastVal === 'true' || lastVal === 'false'
        const expired = !lastTs || now - lastTs > ttlMs
        try {
          let hasPending: boolean | null = null
          if (!expired && cachedOk) {
            hasPending = lastVal === 'true'
          } else {
            const resp = await TASK_API.getGateTodayStatus()
            hasPending = !!resp.hasPending
            localStorage.setItem('GATE_TODAY_STATUS', String(hasPending))
            localStorage.setItem('GATE_TODAY_STATUS_TS', String(now))
          }
          if (hasPending) {
            next('/gate/tasks')
            return
          }
        } catch (e) {
          // 忽略异常，继续正常导航
        }
      }
      next()
      // else {
      //   // 未登录
      //   const permissionStore = usePermissionStore();
      //   console.log("permissionStore.routesLoaded", permissionStore.routesLoaded);
      //   // 判断路由是否加载完成
      //   if (permissionStore.routesLoaded) {
      //     if (to.matched.length === 0) {
      //       // 路由未匹配，跳转到404
      //       next("/404");
      //     } else {
      //       // 动态设置页面标题
      //       const title = (to.params.title as string) || (to.query.title as string);
      //       if (title) {
      //         to.meta.title = title;
      //       }
      //       next();
      //     }
      //   } else {
      //     try {
      //       // 生成动态路由
      //       const dynamicRoutes = await permissionStore.generateRoutes();
      //       dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route));
      //       next({ ...to, replace: true });
      //     } catch (error) {
      //       console.error(error);
      //       // 路由加载失败，重置 token 并重定向到登录页
      //       await useUserStore().resetAllState();
      //       redirectToLogin(to, next);
      //       NProgress.done();
      //     }
      //   }
      // }
    } else {
      // 未登录，判断是否在白名单中
      if (whiteList.includes(to.path)) {
        next()
      } else {
        // 不在白名单，重定向到登录页
        redirectToLogin(to, next)
        NProgress.done()
      }
    }
  })

  // 后置守卫，保证每次路由跳转结束时关闭进度条
  router.afterEach(() => {
    NProgress.done()
  })
}

// 重定向到登录页
function redirectToLogin(
  to: RouteLocationNormalized,
  next: NavigationGuardNext,
) {
  const params = new URLSearchParams(to.query as Record<string, string>)
  const queryString = params.toString()
  const redirect = queryString ? `${to.path}?${queryString}` : to.path
  next(`/login?redirect=${encodeURIComponent(redirect)}`)
}

/** 判断是否有权限 */
export function hasAuth(
  value: string | string[],
  type: 'button' | 'role' = 'button',
) {
  const { roles, perms } = useUserStore().userInfo

  // 超级管理员 拥有所有权限
  if (type === 'button' && roles.includes(ROLE_ROOT)) {
    return true
  }

  const auths = type === 'button' ? perms : roles
  return typeof value === 'string'
    ? auths.includes(value)
    : value.some((perm) => auths.includes(perm))
}
